package pl.pelcra.cesar.spider.data;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;

import pl.pelcra.cesar.data.interfaces.ICommonData;

/**
 * Class stores the map id and url. Id - this is id of record page from database
 * url - url link of attachment for this record
 * 
 * @author margielewski
 * 
 */
public class AttachmentThreadData implements
		ICommonData<Map.Entry<Integer, String>> {

	private Boolean isDataPutting = true;
	private final BlockingQueue<Map.Entry<Integer, String>> listValues = new ArrayBlockingQueue<Map.Entry<Integer, String>>(
			2048, true);

	private final Logger logger = Logger
			.getLogger(AttachmentThreadData.class);

	/**
	 * set variable isDataPutting = false when isDataPutting is false it means
	 * that thread ends putting data to this class
	 */
	@Override
	public synchronized void endPutting() {
		this.isDataPutting = false;
		notify();
	}

	/**
	 * @return return first record from list if not empty or return null object
	 */
	@Override
	public Map.Entry<Integer, String> get() {
		try {
			return this.listValues.take();
		} catch (InterruptedException e) {
			this.logger.info(e.getMessage());
			return null;
		}
	}

	/**
	 * @return return true - map is empty and thread end putting data on map,
	 *         return false - map is not empty or thread doesn't end putting
	 *         data to map
	 */
	@Override
	public boolean isEndPutting() {
		return this.listValues.isEmpty() && !this.isDataPutting;
	}

	/**
	 * put data to map
	 * 
	 * @param id
	 *            id of record from database
	 * @param urlAttachment
	 *            url link
	 */
	@Override
	public void put(Map.Entry<Integer, String> value) {
		try {
			this.listValues.put(value);
			this.logger.info(String.format("AttachmentThreadData URLs = %s",
					this.listValues.size()));
		} catch (InterruptedException e) {
			this.logger.info(e.getMessage());
		}
	}

	/**
	 * put data to map
	 * 
	 * @param tmpMapWebRecordUrlAttachment
	 *            object of treeMap
	 */
	public void putAll(TreeMap<Integer, String> tmpMapWebRecordUrlAttachment) {
		for (Map.Entry<Integer, String> entry : tmpMapWebRecordUrlAttachment
				.entrySet()) {
			this.put(entry);
		}
	}
}
